public class 最长公共前缀 {

    public static void main(String[] args) {
        String[] strings = {"cir","car"};
        System.out.println(longestCommonPrefix(strings));
    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs.length == 1)
            return strs[0];

        int k = Math.min(strs[0].length(), strs[1].length());
        String result = strs[0].length() < strs[1].length() ? strs[0] : strs[1];
        for (int i = 0; i < k; i++) {
            char a = strs[0].charAt(i);
            char b = strs[1].charAt(i);
            if (a != b) {
                result = strs[0].substring(0, i);
                k = result.length();
            }
        }
        for (int i = 2; i < strs.length; i++) {
            if (strs[i].length() < result.length()) {
                result = result.substring(0, strs[i].length());
            }
            for (int j = 0; j < result.length(); j++) {
                char a = result.charAt(j);
                char b = strs[i].charAt(j);
                if (a != b) {
                    result = result.substring(0, j);
                    break;
                }
            }
        }
        return result;
    }
}
